package com.tool.builder.BuildClass;

import com.tool.bean.Constants;
import com.tool.bean.FieldInfo;
import com.tool.bean.TableInfo;
import com.tool.builder.BuildHelper.BuildComment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * 创建po包
 */
public class BuildQuery {
    private static final Logger logger = LoggerFactory.getLogger(BuildQuery.class);

    public static void execute(TableInfo tableInfo) {
        File folder = new File(Constants.PATH_QUERY);
        if(!folder.exists()) {   // 路径不存在则创建
            folder.mkdirs();
        }

        String className = tableInfo.getBeanName() + Constants.SUFFIX_BEAN_QUERY;

        File queryFile = new File(folder, className + ".java");

        OutputStream out = null;
        OutputStreamWriter outw = null;
        BufferedWriter bw = null;
        try {
            out = new FileOutputStream(queryFile);
            outw = new OutputStreamWriter(out, "utf8");
            bw = new BufferedWriter(outw);

            bw.write("package " + Constants.PACKAGE_QUERY + ";");
            bw.newLine();
            bw.newLine();

            bw.write("import lombok.Data;");
            bw.newLine();

            if(tableInfo.getHaveDate() || tableInfo.getHaveDateTime()) {
                bw.write("import java.util.Date;");
                bw.newLine();
            }

            if(tableInfo.getHaveBigDecimal()) {
                bw.write("import java.math.BigDecimal;");
                bw.newLine();
            }
            bw.newLine();

            // 构建类注释
            BuildComment.createClassComment(bw, tableInfo.getComment() + "查询对象");
            bw.newLine();
            bw.newLine();

            bw.write("@Data");
            bw.newLine();
            bw.write("public class " + className + " {");
            bw.newLine();

            for(FieldInfo field : tableInfo.getFieldList()) {
                BuildComment.createFieldComment(bw, field.getComment());

                bw.write("\tprivate " + field.getJavaType() + " " + field.getPropertyName() + ";");
                bw.newLine();
                bw.newLine();

            }

            bw.write("}");
            bw.flush();
        }   catch (Exception e) {
            logger.error("创建Query失败", e);
        }  finally {
            if(outw !=null) {
                try {
                    outw.close();
                }   catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
